﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using SnippetBox.Core.Data.Models;

namespace SnippetBox.Core.Data.Repository {
    public class Repository<T> : IRepository<T> where T : class, IDeletable {
        private readonly DbSet<T> _dbSet;
        private readonly DbContext _context;

        public Repository(DbContext context) {
            _context = context;
            _dbSet = context.Set<T>();
        }

        public IQueryable<T> GetAll() {
            return _dbSet.Where(m => !m.IsDeleted);
        }

        public T GetById(int id) {
            return _dbSet.Find(id);
        }

        public IQueryable<T> Where(Expression<Func<T, bool>> where) {
            return _dbSet.Where(where);
        }

        public T SingleOrDefault(Expression<Func<T, bool>> where) {
            return _dbSet.SingleOrDefault(where);
        }

        public T FirstOrDefault(Expression<Func<T, bool>> where) {
            return _dbSet.FirstOrDefault(where);
        }

        public void Delete(T entity) {
            _dbSet.Remove(entity);
        }

        public void Add(T entity) {
            _dbSet.Add(entity);
        }

        public void Attach(T entity) {
            _dbSet.Attach(entity);
        }

        public void SaveChanges() {
            _context.SaveChanges();
        }
    }
}